package demo.topic17;

import jdk.internal.org.xml.sax.Attributes;
import jdk.internal.org.xml.sax.SAXException;
import jdk.internal.org.xml.sax.helpers.DefaultHandler;

import java.util.ArrayList;
import java.util.List;

/**
 * 继承 DefaultHandler
 * 需要重写 startDocument、endDocument、startElement、endElement、characters
 */
public class PersonHandler extends DefaultHandler {
    private List<Person> persons = null;
    private Person p; // 记录当前正在解析的person对象
    private String tag; // 记录当前正在解析的标签名


    @Override
    public void startDocument() throws SAXException {
        super.startDocument();
        persons = new ArrayList<>();
        System.out.println("开始解析文档...");
    }

    @Override
    public void endDocument() throws SAXException {
        super.endDocument();
        System.out.println("解析文档结束");
    }

    /**
     * 开始解析元素
     * @param s 命名空间
     * @param s1 不带前缀的标签名
     * @param s2 带前缀的标签名
     * @param attributes 当前标签的属性集合
     * @throws SAXException
     */
    @Override
    public void startElement(String s, String s1, String s2, Attributes attributes) throws SAXException {
        super.startElement(s, s1, s2, attributes);
        if ("person".equals(s2)) {
            p = new Person();
            String personid = attributes.getValue("personid");
            p.setPersonid(personid);
        }
        tag = s2;
    }

    @Override
    public void endElement(String s, String s1, String s2) throws SAXException {
        super.endElement(s, s1, s2);
        if ("person".equals(s2)) {
            persons.add(p);
            p = null;
            tag = null;
        }
    }

    @Override
    public void characters(char[] chars, int i, int i1) throws SAXException {
        super.characters(chars, i, i1);
        if(tag != null) {
            if("name".equals(tag)) {
                p.setName(new String(chars, i, i1));
            } else if("address".equals(tag)) {
                p.setAddress(new String(chars, i, i1));
            } else if("tel".equals(tag)) {
                p.setTel(new String(chars, i, i1));
            } else if("fax".equals(tag)) {
                p.setFax(new String(chars, i, i1));
            } else if("email".equals(tag)) {
                p.setEmail(new String(chars, i, i1));
            }
        }
    }
}
